/**
 * https://leetcode.cn/problems/amount-of-time-for-binary-tree-to-be-infected/submissions/583898755/
 * 2385. 感染二叉树需要的总时间
 * medium 陈贝纯 2024.11.29
 * 换根dp
 */

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int ans=0;
    int dfs(TreeNode* root,int s){
        if(!root)
        return 0;
        int l=dfs(root->left,s);
        int r=dfs(root->right,s);
        if(root->val==s){
            ans=max(l,r);
            return -1;
        }
        if(l>=0&&r>=0)
        return max(l,r)+1;
        ans=max(ans,abs(l-r));
        return min(l,r)-1;
    }
    int amountOfTime(TreeNode* root, int start) {
        dfs(root,start);
        return ans;
    }
};